package com.ibiaoke.common.utils;


import com.ibiaoke.common.cache.EhCacheKit;
import com.ibiaoke.common.configs.GlobalConfigs;
import com.ibiaoke.common.configs.GlobalConfigsKey;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by huhaichao on 2017/5/16.
 */
public class SmsUtil {

    public static long SMS_SEND_LIMIT = 1 * 60 * 1000;
    public static long SMS_TIME_AFFECTS = 2 * 60 * 1000;
    public static final String SMS_WITH_URL_FLAG = "请点击链接查看商品详情";
    private static Logger logger = LoggerFactory.getLogger(SmsUtil.class);
    private static String MSG_TEMPLATE_COUPON_ARRIVE = "JSM40225-0007";
    private static String MSG_TEMPLATE_VERIFY_CODE = "JSM40225-0002";

    /**
     * 发送模板短信
     *
     * @param mobile
     * @param tmplate
     * @param content
     * @return
     */
    public static String sendMsg(String mobile, String tmplate, String content) {
        logger.info("发送短信开始，手机：{}", mobile);
        Map<String, String> map = new HashMap<String, String>();
        map.put("method", "sendMsg");
        map.put("username", "JSM40225");//此处填写用户账号
        map.put("password", "2z4jdhhr");//此处填写用户密码
        map.put("veryCode", "6ksjpzqkfiqu");
        map.put("mobile", mobile);//此处填写发送号码
        map.put("tempid", tmplate);//此处填写模板短信编号
        map.put("content", content);//此处填写模板短信内容
        map.put("msgtype", "2");
        String str = HttpPost.doPost("http://112.74.76.186:8030/service/httpService/httpInterface.do", map, "GBK");
        logger.info("发送短信结束，手机：{}，短信模板：{}，短信内容：{}。\n返回码:{}", mobile, tmplate, content, str);
        return str;
    }

    /**
     * 发送订单模板短信
     * 尊敬的【@1@】店长您好，您有新的让我来订单，请及时处理！
     * 【订单号】 @2@
     * 【商品详情】
     *
     * @param content @1@=浦口店,@2@=201708286783,@3@=香蕉(箱*2),@4@=陈诚,@5@=13888888888,@6@=江苏省南京市建邺区
     * @return
     * @3@ 【收货人姓名】 @4@
     * 【收货人电话】 @5@
     * 【收货人地址】 @6@
     */
    public static String sendOrderMsgWithTemp(String mobile, String template, String content) {
        return sendMsg(mobile, template, content);
    }

    public static String sendCouponArriveMsgWithTemp(String mobile){
        return sendMsg(mobile, MSG_TEMPLATE_COUPON_ARRIVE,"@1@=");
    }

    public static String sendVerifyCode(String mobile) {
        validate(mobile);
        String code = randomSmsCode();
        sendMsg(mobile, MSG_TEMPLATE_VERIFY_CODE, "@1@=" + code);
        EhCacheKit.getInstance().put(CommonConsts.SMS_CACHE_NAME, mobile, new SmsBeanUtils(mobile, code));
        return code;
    }

    private static void validate(String mobile) {
        AssertUtils.notBlank(mobile, "手机号码不能为空");
        SmsBeanUtils smsUtil = (SmsBeanUtils) EhCacheKit.getInstance().get(CommonConsts.SMS_CACHE_NAME, mobile);
        if (smsUtil != null) {
            long leftSec = (SMS_SEND_LIMIT- (System.currentTimeMillis() - smsUtil.getTime())) / 1000;
            AssertUtils.requireTrue(leftSec <= 0, "请" + leftSec + "秒后重新发送");
        }
    }

    public static String randomSmsCode() {
        return RandomUtils.randomNumber(6);
    }


    public static void validateMobileCode(String mobile, String code) {
        AssertUtils.notBlank(mobile,"手机号码不能为空");
        AssertUtils.notBlank(code,"验证码不能为空");
        SmsBeanUtils smsUtil = (SmsBeanUtils) EhCacheKit.getInstance().get(CommonConsts.SMS_CACHE_NAME, mobile);
        AssertUtils.notNull(smsUtil,"请先获取验证码");
        AssertUtils.requireEquals(mobile, smsUtil.getMobile(), "验证码错误");
        AssertUtils.requireEquals(code, smsUtil.getCode(), "验证码错误");
        AssertUtils.requireTrue(System.currentTimeMillis() - smsUtil.getTime() < SmsUtil.SMS_TIME_AFFECTS, "验证码超时");
        AssertUtils.requireEquals(code, smsUtil.getCode(), "验证码错误");
        EhCacheKit.getInstance().remove(CommonConsts.SMS_CACHE_NAME, mobile);
    }
}
